<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    
    .box1{width: 100px;height: 100px;background: red;position: absolute;left:0;top:0;}

  </style>
</head>
<body>
  <div class="box1"></div>
</body>
<script>


  function Drag(ele){
    this.ele = ele;

    // 初始立即读取本地存储中的位置信息（注意默认值）
    const l = localStorage.getItem("left") || 0;
    const t = localStorage.getItem("top") || 0;
    // 设置给元素
    this.ele.style.left = l + "px";
    this.ele.style.top = t + "px";

    this.addEvent();
  }
  Drag.prototype.addEvent = function(){
    const that = this;
    this.ele.onmousedown = function(eve){
      that.downE = eve || window.event;
      document.onmousemove = function(eve){
        that.moveE = eve || window.event;
        that.move()
      }
      document.onmouseup = function(){
        that.up()
      }
    }
  }
  Drag.prototype.move = function(){
    this.ele.style.left = this.moveE.pageX - this.downE.offsetX + "px";
    this.ele.style.top = this.moveE.pageY - this.downE.offsetY + "px";
  }
  Drag.prototype.up = function(){
    document.onmousemove = document.onmouseup = null;

    // 鼠标抬起时，存储元素的当前位置，以备下次使用
    localStorage.setItem("left", this.ele.offsetLeft)
    localStorage.setItem("top", this.ele.offsetTop)
  }

  const box1 = document.querySelector(".box1");

  new Drag(box1);
</script>
</html>